#!/usr/bin/perl -w # for syntax highlighting
package clreqd_modules;

#########################################################################
# This rountine takes DBTYPE and SQL and returns the matching rows,	#
# if a SELECT statement or OK|FAILED if other SQL.			#
#									#
# Makes use of ::msg, ::warning and ::error when needbe.		#
#									#
# No locking here since SQLite performs that.				#
#########################################################################

use cldb;
use clstatdb;
use clmasterdefaults;
use Data::Dumper;

sub perform_adhoc_sql {
my %ARGS=@_;
my $f;
my $db=uc($ARGS{DBTYPE});
my $sql=$ARGS{SQL};
my $conn;

	if($db ne "CONFIG" && $db ne "STATUS") {
		return "ERROR Unknown DB type (should be 'config' or 'status').";
	}

	if($db eq "CONFIG") {
		$conn=new cldb("$::ENV{TRUECL_CFG}/config.db");
	} else {
		$conn=new clstatdb("$::ENV{TRUECL_CFG}/status.db");
	}
	if(!defined($conn)) {
		return "ERROR Unable to make connection to '$db' database.";
	}

	my $href;
	if($sql =~ /\s*SELECT\s+/i) {
		$href=$conn->get_rows($sql);
		if(!defined($href)) {
			return "FAIL Error occured running SQL statement!";
		}
	} else {
		my $r=$conn->do($sql);
		if(!$r) {
			return "FAIL " . ($conn->error)[1];
		}
		return "OK";
	}

	#################################################################
	# It was a query that worked, so return any results...		#
	#################################################################

	my @F=(keys(%{$href->[0]}));
	if(! @F) {
		return "ERROR No matching records!";
	}
	@F=sort(@F);
	$r=join("|",@F);
	for (@$href) {
		my @x=();
		my $field;
		for $field (@F) {
			my $y=$_->{$field};
			$y="" if !defined($y);
			$y =~ s/\n//g;
			push @x,$y;
		}
		$r.="\n" . join("|",@x);
	}
	return $r;
}

1;
